﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Diagnostics;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ServiceModel;

using QCM.Framework;
using QCM.Forms.Properties;
using QCM.Forms.ServiceReference1;

namespace QCM.Forms
{
    public partial class Form1 : Form
    {
        ServiceReference1.ContractContractClient proxy;
        Font fontTitleQuestion = null;

        public Form1()
        {
            Trace.WriteLine("Démarrage de Form1","Catégorie");
            this.fontTitleQuestion = Settings.Default.FontTitleQuestion;
            InitializeComponent();
            splitContainer1.Panel2.Enabled = false;
        }

        private void RefreshTreeView_Click(object sender, EventArgs e)
        {
            this.treeView1.Nodes.Clear();
            ServiceReference1.Categorie[] cats;

            //Recupere la liste des categoories en interrogeant le service
            try
            {
                cats = proxy.GetCategories();
            }
            catch (FaultException<ServiceReference1.SQLFaultException> exp)
            {
                MessageBox.Show("Reason:" + exp.Detail.reason + "Code: " + exp.Detail.code, "SQLFaultException");
                cats = null;
            }
            catch (FaultException exp)
            {
                MessageBox.Show("Reason:" + exp.Reason + "Code: " + exp.Code.Name, "FaultException");
                cats = null;
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.GetType().ToString());
                cats = null;
            }
            finally
            {
                this.toolStripStatusLabel2.Text = proxy.State.ToString();
            }
            //Ajoute des categories dans le treeView
            if (cats != null)
            {
                foreach (ServiceReference1.Categorie cat in cats)
                {
                    TreeNode tn = new TreeNode(cat.Nom) { Name = cat.Nom };
                    tn.Tag = cat.idCategorie;

                    if (cat.NomMere == string.Empty)
                    {
                        this.treeView1.Nodes.Add(tn);
                    }
                    else
                    {
                        TreeNode[] treeNodes = treeView1.Nodes.Find(cat.NomMere, true);
                        if (treeNodes.Length == 1)
                        {
                            treeNodes[0].Nodes.Add(tn);
                        }
                        else
                        {
                            throw new Exception("Problème de catégorie: " + cat.NomMere + ", cette categorie n'existe pas ou est en doublon");
                        }

                    }
                    //On ajoute a la nouvelle categorie les questionnaires associés
                    try
                    {
                        ShortQuestionnaire[] questionnaires = proxy.GetQuestionnaires((int)tn.Tag);
                        foreach (ShortQuestionnaire quest in questionnaires)
                        {
                            TreeNode tnQuest = new TreeNode(quest.Nom);
                            tnQuest.Tag = quest;
                            tn.Nodes.Add(tnQuest);
                        }
                    }
                    catch (FaultException<ServiceReference1.SQLFaultException> exp)
                    {
                        MessageBox.Show("Reason:" + exp.Detail.reason + "Code: " + exp.Detail.code, "SQLFaultException");
                    }
                    catch (FaultException exp)
                    {
                        MessageBox.Show("Reason:" + exp.Reason + "Code: " + exp.Code.Name, "FaultException");
                    }
                    catch (Exception exp)
                    {
                        MessageBox.Show(exp.GetType().ToString());
                    }

                }
            }
        }
        
        ServiceReference1.Questionnaire selectedQuestionnaire;
        private void treeView1_BeforeSelect(object sender, TreeViewCancelEventArgs e)
        {
            if (e.Node.Tag != null)
            {
                try
                {
                    selectedQuestionnaire = proxy.GetQuestionnaire(((ShortQuestionnaire)e.Node.Tag).Id); ;
                    splitContainer1.Panel2.Enabled = true;
                    this.textBox1.Text = selectedQuestionnaire.Descriptif;
                    this.label4.Text = selectedQuestionnaire.nbQuestions.ToString();
                    this.ModeQCMCbx.SelectedIndex = 0;
//                    selectedQuestionnaire.Questions.Reverse();

                }
                catch (FaultException<ServiceReference1.SQLFaultException> exp)
                {
                    MessageBox.Show("Reason:" + exp.Detail.reason + "Code: " + exp.Detail.code, "SQLFaultException");
                    selectedQuestionnaire = null;
                }
                catch (FaultException exp)
                {
                    MessageBox.Show("Reason:" + exp.Reason + "Code: " + exp.Code.Name, "FaultException");
                    selectedQuestionnaire = null;
                }
                catch (Exception exp)
                {
                    MessageBox.Show(exp.GetType().ToString());
                    selectedQuestionnaire = null;
                }
            }

            else
            {
                splitContainer1.Panel2.Enabled = false;
                selectedQuestionnaire = null;
                this.textBox1.Text = string.Empty;
                this.label4.Text = "0";
                this.panel1.Controls.Clear();
            }
        }

        private void chargerUneFontToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FontDialog fd = new FontDialog();
            if (fd.ShowDialog() == DialogResult.OK)
            {
                fontTitleQuestion = fd.Font;
                foreach (Object qctrl in panel1.Controls)
                {
                    if(qctrl.GetType() == typeof(QuestionCtrl))
                        ((QuestionCtrl)qctrl).FontTitle = fontTitleQuestion;
                }
            }
        }

        private void hTTPSToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //TODO : améliorer l'authentification :
            //http://dotnet.developpez.com/mvc/mvc-authentification-windows/
            try
            {
                LoginForm inputForm = new LoginForm();
                inputForm.ShowDialog();
                if (inputForm.getLogin() != null && inputForm.getPassword() != null)
                {
                    PermissiveCertificatePolicy.Enact("CN=HTTPS-Server");
                    this.proxy = new QCM.Forms.ServiceReference1.ContractContractClient("newEndpoint");
                    this.proxy.ClientCredentials.UserName.UserName = "HBMacProWin7\\"+inputForm.getLogin();
                    this.proxy.ClientCredentials.UserName.Password = inputForm.getPassword();
                    this.toolStripStatusLabel2.Text = this.proxy.State.ToString();
                }
            }
            catch (FaultException<ServiceReference1.SQLFaultException> exp)
            {
                MessageBox.Show("Reason:" + exp.Detail.reason + "Code: " + exp.Detail.code, "SQLFaultException");
            }
            catch (FaultException exp)
            {
                MessageBox.Show("Reason:" + exp.Reason + "Code: " + exp.Code.Name, "FaultException");
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.GetType().ToString());
            }
        }

        private void hTTPToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                this.proxy = new QCM.Forms.ServiceReference1.ContractContractClient("oldEndpoint");
                this.toolStripStatusLabel2.Text = this.proxy.State.ToString();
            }
            catch (FaultException<ServiceReference1.SQLFaultException> exp)
            {
                MessageBox.Show("Reason:" + exp.Detail.reason + "Code: " + exp.Detail.code, "SQLFaultException");
            }
            catch (FaultException exp)
            {
                MessageBox.Show("Reason:" + exp.Reason + "Code: " + exp.Code.Name, "FaultException");
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.GetType().ToString());
            }
        }

        Question[] questions;
        Int32 currentQuestion = 0;
        List<int> reponses = new List<int>();

        private void startBtn_Click(object sender, EventArgs e)
        {
            questions = proxy.GetQuestions(selectedQuestionnaire.Id);
            DisplayQuestion(currentQuestion);
            /*foreach (ServiceReference1.Question quest in questions)
            {
                QuestionCtrl ctrl = new QuestionCtrl();
                this.panel1.Controls.Add(ctrl);

                ctrl.Dock = System.Windows.Forms.DockStyle.Top;
                ctrl.FontTitle = fontTitleQuestion;
                ctrl.Name = quest.Titre;
                QCM.Framework.QuestionCtrl.Question question = new QuestionCtrl.Question(quest.Titre, quest.Id);
                foreach (Reponse rep in quest.Reponses) 
                {
                    question.Reponses.Add(new QuestionCtrl.Reponse(rep.Text, rep.Valeur));
                }
                ctrl.LaQuestion = question;
            }*/

        }

        RadioButton[] rdBtns;

        private void DisplayQuestion(int idQuestion)
        {
            Question quest = questions[idQuestion];
            this.panel1.Controls.Clear();

            Label lblQuest = new Label();
            lblQuest.Width = quest.Titre.Count() * 5;
            lblQuest.Font = fontTitleQuestion;
            lblQuest.Dock = System.Windows.Forms.DockStyle.Top;
            lblQuest.Text = quest.Titre;
            this.panel1.Controls.Add(lblQuest);

            Int32 counter = 0;
            rdBtns = new RadioButton[quest.Reponses.Count()];
            foreach(Reponse rep in quest.Reponses) 
            {
                RadioButton rdBtn = new RadioButton();
                rdBtn.Width = 150;
                rdBtn.Left = lblQuest.Left;
                rdBtn.Top = lblQuest.Top + (lblQuest.Height * counter) + 20;
                rdBtns[counter] = rdBtn;
                counter++;
                rdBtn.Text = rep.Text;
                this.panel1.Controls.Add(rdBtn);
            }

            this.prevButton.Enabled = (currentQuestion > 0);
            this.nextButton.Enabled = (currentQuestion < questions.Count() - 1);
            this.submitButton.Visible = (currentQuestion == questions.Count() - 1);

        }

        Int32 ModeQCMSelected;
        private void ModeQCMCbx_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.ModeQCMSelected = this.ModeQCMCbx.SelectedIndex;
        }

        private void nextButton_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < rdBtns.Count(); i++)
            {
                if (((RadioButton)rdBtns[i]).Checked)
                {
                    reponses.Insert(currentQuestion, ((Reponse)questions[currentQuestion].Reponses.GetValue(i)).Valeur);
                    break;
                }
            }

            currentQuestion++;
            DisplayQuestion(currentQuestion);
        }

        private void prevButton_Click(object sender, EventArgs e)
        {
            currentQuestion--;
            DisplayQuestion(currentQuestion);
        }

        private void submitButton_Click(object sender, EventArgs e)
        {
            ResultForm resultForm = new ResultForm();
            switch (ModeQCMSelected)
            {
                case 0:
                    resultForm.showResult(true);
                    break;
                case 1:
                    resultForm.showScore(60);
                    //int note = proxy.Correction(reponses.ToArray<int>());
                    break;
                default:
                    break;
            }
        }

    }
}
